import request from '../utils/request.jsx';

/**
 * 用户登录
 * @param {Object} data - 登录信息
 * @param {string} data.username - 用户名
 * @param {string} data.password - 密码
 * @returns {Promise}
 */
export async function login(data) {
  try {
    const response = await request.post('/auth-center/auth/login', data);
    // 保存token到localStorage
    if (response.code === 200 && response.token) {
      localStorage.setItem('token', response.token);
      localStorage.setItem('userInfo', JSON.stringify(response.userInfo || {}));
    }
    return response;
  } catch (error) {
    console.error('登录失败:', error);
    // 确保返回的错误对象包含code和message属性，与login/index.tsx的处理逻辑一致
    throw {
      code: error?.response?.data?.code || 500,
      message: error?.response?.data?.message || '登录失败，请检查网络或用户名密码'
    };
  }
}

/**
 * 用户注册
 * @param {Object} data - 注册信息
 * @returns {Promise}
 */
export async function register(data) {
  try {
    return await request.post('/auth-center/auth/register', data);
  } catch (error) {
    console.error('注册失败:', error);
    throw error;
  }
}

/**
 * 获取用户信息
 * @returns {Promise}
 */
export async function getUserInfo() {
  try {
    // 先从localStorage获取用户信息
    const userInfoStr = localStorage.getItem('userInfo');
    if (userInfoStr) {
      try {
        return JSON.parse(userInfoStr);
      } catch (e) {
        console.warn('解析用户信息失败，重新从服务器获取');
      }
    }
    // 检查是否有token，如果没有则不发送请求
    const token = localStorage.getItem('token');
    if (!token) {
      console.log('没有token，不发送用户信息请求');
      return null;
    }
    
    // 从服务器获取用户信息 - 修复API路径
    const response = await request.get('/auth-center/auth/getCurrentUserInfo');
    // 保存到localStorage
    localStorage.setItem('userInfo', JSON.stringify(response));
    return response;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    // 不要在无token情况下抛出错误，避免导致循环请求
    const token = localStorage.getItem('token');
    if (!token) {
      return null;
    }
    throw error;
  }
}

/**
 * 刷新token
 * @returns {Promise}
 */
export async function refreshToken() {
  try {
    const response = await request.post('/auth-center/auth/refreshToken');
    if (response.token) {
      localStorage.setItem('token', response.token);
    }
    return response;
  } catch (error) {
    console.error('刷新token失败:', error);
    throw error;
  }
}

/**
 * 用户登出
 * @returns {Promise}
 */
export async function logout() {
  try {
    await request.post('/auth-center/auth/logout');
  } catch (error) {
    console.error('登出失败:', error);
  } finally {
    // 清除localStorage中的用户信息和token
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    window.location.href = '/login';
  }
}